package com.itcs.pap.tran;

import com.alibaba.fastjson.JSON;
import com.itcs.box.BoxConstants;
import com.itcs.box.domain.BoxData;
import com.itcs.box.domain.BoxRequest;
import com.itcs.box.domain.BoxResponse;
import com.itcs.box.util.DateUtils;
import com.itcs.box.util.LogUtils;
import com.itcs.eureka.service.PayApiFeignClientService;
import com.itcs.trading.mapper.OwnerLaneMapper;
import com.itcs.trading.mapper.TerminalInfoMapper;
import com.itcs.trading.mapper.TerminalLinksRgtMapper;
import com.itcs.trading.model.OwnerLane;
import com.itcs.trading.model.TerminalInfo;
import com.itcs.trading.model.TerminalLinksRgt;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName: Tran1001
 * @Description: 连接登录消息
 * @author CHEN-HF
 * @date 2017年12月19日 下午8:47:45
 * 
 */
@Component
public class BoxTran1001 implements PayApiFeignClientService {

	@Autowired
	private TerminalInfoMapper terminalInfoMapper;

	@Autowired
	private TerminalLinksRgtMapper terminalLinksRgtMapper;
	@Autowired
	private OwnerLaneMapper ownerLaneMapper;

	private Log logger = LogFactory.getLog(getClass());

	/**支付链接地址*/
	@Value("${payUrl}")
	private String payUrl;
	/**设备校验开关*/
	@Value("${terminal_flag:true}")
	private boolean terminalFlag;
	/**车道交易开关*/
	@Value("${lane_flag:true}")
	private boolean laneFlag;

	@Override
	public String getTrancode() {
		return "box_1001";
	}

	public String getTranDescription() {
		return "连接登录消息";
	}

	private void setIinitRepMessage(BoxRequest boxRequest, BoxResponse boxResponse) {
		// 设置返回消息类型代码
		boxResponse.setMessgeType("2001");
		boxResponse.getData().setDeviceId(boxRequest.getData().getDeviceId());
		boxResponse.getData().setLaneId(boxRequest.getData().getLaneId());
		boxResponse.getData().setPayUrl(payUrl);
		logger.info("支付链接地址:[" + payUrl + "]");
	}

	/**
	 * 作用:
	 * 场景:
	 * 其他: 登录结果：0：登陆成功，-1，密码验证失败，-2：无此设备
	 * @Title exchange
	 * @Date: 2019-05-17 16:49
	 * @param serverId
	 * @param trancode
	 * @param reqRecord
	 * @return java.util.Map<java.lang.String,java.lang.Object>
	 * @throws
	 */
	@Override
	@RequestMapping(value = "/box_1001", method = RequestMethod.POST, produces = "application/json")
	public Map<String, Object> exchange(String serverId, String trancode,
										@RequestParam Map<String, Object> reqRecord) {

		logger.info(LogUtils.build(getTrancode(), getTranDescription(),
				"接收登录请求", JSON.toJSONString(reqRecord)));

		BoxResponse boxResponse = new BoxResponse();
		BoxData responseData = new BoxData();
		boxResponse.setData(responseData);

		Map<String, Object> res = new HashMap<>();
		try {
			BoxRequest boxRequest = (BoxRequest) reqRecord.get(BoxConstants.BOX_REQ_KEY);
			this.setIinitRepMessage(boxRequest, boxResponse);
			// 业务处理
			boxResponse = this.handle(boxRequest, boxResponse);
			responseData.setReplyTime(DateUtils.getUnixTimeStamp());
		} catch (Exception e) {
			// 其他异常或数据库异常
			responseData.setResult("9");
			logger.error(LogUtils.build(getTrancode(), getTranDescription(),
					"处理失败" + e.getMessage(),
					JSON.toJSONString(reqRecord)), e);
		}
		res.put(BoxConstants.BOX_RES_KEY, boxResponse);

		logger.info(LogUtils.build(getTrancode(), getTranDescription(),
				"返回登陆回复信息(2001)", JSON.toJSONString(res)));

		return res;
	}

	public BoxResponse handle(BoxRequest boxRequest, BoxResponse boxResponse) {

		BoxData data = boxRequest.getData();
		if (StringUtils.isEmpty(data.getPassword())) {
			// 密码校验失败
			boxResponse.getData().setResult("2");
			return boxResponse;
		}

		// 数据库查找道路、设备
		TerminalInfo lane = terminalInfoMapper.selectByDeviceId(data.getDeviceId());
		// && lane.getLaneId().equals(data.getLaneId()) 暂时不验证laneId
		if (lane != null && lane.getLaneId() != null) {
			if (!data.getPassword().equals(lane.getTerminalPwd())) {
				logger.info("连接登录[2-密码校验失败]");
				// 密码校验失败
				data.setResult("2");
				return boxResponse;
			}
			if(terminalFlag){
				//车道验证
				if (!data.getLaneId().equals(lane.getLaneId())) {
					logger.info("连接登录[3-车道信息不匹配]");
					// 车道信息不匹配
					data.setResult("3");
					return boxResponse;
				}
			}
			OwnerLane ownerLane = ownerLaneMapper.selectByPrimaryKey(data.getLaneId());
			if (ownerLane==null) {
				logger.info("连接登录[3-查无此车道]");
				// 车道信息不匹配
				data.setResult("3");
				return boxResponse;
			}

			// 写入盒子链接信息
			TerminalLinksRgt link = new TerminalLinksRgt();
			String channelId = UUID.randomUUID().toString();
			link.setConnectId(channelId);
			boxResponse.setChannelId(channelId);
			link.setTerminalNo(data.getDeviceId());
			Date d = new Date();
			// 连接时间
			link.setLinkTime(d);
			// 连接时间
			link.setLinkHbTime(d);
			// 收费车道编号,收费车道可关联查询收费站、广场、路段信息
			link.setLaneId(lane.getLaneId());
			// 通道连接ip
			link.setLocalhost(boxRequest.getHost());
			// 通道连接端口
			link.setPort(boxRequest.getPort());
			// 登录后状态是否设置为车道交易状态?是设置1不确定设置null
			link.setTerminalStatus(null);
			// 盒子key信息
			link.setTerminalKey(boxRequest.getKey());
			logger.info("记录连接信息："+JSON.toJSONString(link));
			terminalLinksRgtMapper.insert(link);

		} else {
			logger.info("连接登录[3-查无此设备]");
			// 无此设备
			boxResponse.getData().setResult("3");
			return boxResponse;
		}

		// 成功返回
		boxResponse.getData().setResult("1");

		return boxResponse;
	}

}
